# -*- coding: utf-8 -*-
"""
PDF转Word转换器 - 支持批量转换和格式保留
"""

import os
import sys
import threading
from tkinter import *
from tkinter import filedialog, messagebox, ttk
from pdf2docx import Converter
from docx import Document
import time
from datetime import datetime
# ================== 配置区 ==================
AUTHOR_NAME = "ITOP"
WINDOW_TITLE = f"PDF转Word转换器 - 作者: {AUTHOR_NAME}"
# ============================================

class PDFToWordConverter:
    def __init__(self, root):
        self.root = root
        self.root.title(WINDOW_TITLE)
        self.root.geometry("750x550")
        self.root.minsize(600, 450)
        self.root.configure(bg="#f5f5f5")
        
        # 存储转换任务
        self.conversion_thread = None
        self.stop_conversion = False
        self.isAuto=False
        self.setup_ui()
        
    def setup_ui(self):
        """设置用户界面"""
        # 标题栏
        title_frame = Frame(self.root, bg="#2c3e50", height=80)
        title_frame.pack(fill=X, padx=10, pady=10)
        title_frame.pack_propagate(False)
        
        title_label = Label(title_frame, text="PDF转Word转换器", 
                           font=("微软雅黑", 20, "bold"), 
                           fg="white", bg="#2c3e50")
        title_label.pack(expand=True)
        
        subtitle_label = Label(title_frame, text="支持批量转换，保留文本格式", 
                              font=("微软雅黑", 10), 
                              fg="#ecf0f1", bg="#2c3e50")
        subtitle_label.pack(expand=True)
        
        # 主内容区
        main_frame = Frame(self.root, bg="#f5f5f5")
        main_frame.pack(fill=BOTH, expand=True, padx=15, pady=10)
        
        # 文件选择区域
        file_frame = LabelFrame(main_frame, text="文件选择", 
                               font=("微软雅黑", 11, "bold"),
                               bg="#f5f5f5", fg="#2c3e50")
        file_frame.pack(fill=X, pady=(0, 10))
        
        # PDF文件选择
        pdf_label = Label(file_frame, text="PDF文件:", 
                         font=("微软雅黑", 10), bg="#f5f5f5")
        pdf_label.grid(row=0, column=0, sticky=W, padx=5, pady=8)
        
        self.pdf_path = StringVar()
        pdf_entry = Entry(file_frame, textvariable=self.pdf_path, 
                         width=50, font=("微软雅黑", 9))
        pdf_entry.grid(row=0, column=1, padx=5, pady=8)
        
        pdf_btn = Button(file_frame, text="选择PDF文件", 
                        command=self.select_pdf_file,
                        font=("微软雅黑", 9), bg="#3498db", fg="white")
        pdf_btn.grid(row=0, column=2, padx=5, pady=8)
        
        # 输出目录选择
        output_label = Label(file_frame, text="输出目录:", 
                           font=("微软雅黑", 10), bg="#f5f5f5")
        output_label.grid(row=1, column=0, sticky=W, padx=5, pady=8)
        
        self.output_path = StringVar()
        output_entry = Entry(file_frame, textvariable=self.output_path, 
                           width=50, font=("微软雅黑", 9))
        output_entry.grid(row=1, column=1, padx=5, pady=8)
        
        output_btn = Button(file_frame, text="选择输出目录", 
                          command=self.select_output_folder,
                          font=("微软雅黑", 9), bg="#27ae60", fg="white")
        output_btn.grid(row=1, column=2, padx=5, pady=8)
        
        # 转换选项区域
        options_frame = LabelFrame(main_frame, text="转换选项", 
                                  font=("微软雅黑", 11, "bold"),
                                  bg="#f5f5f5", fg="#2c3e50")
        options_frame.pack(fill=X, pady=(0, 10))
        
        # 页面范围选择
        page_label = Label(options_frame, text="页面范围:", 
                          font=("微软雅黑", 10), bg="#f5f5f5")
        page_label.grid(row=0, column=0, sticky=W, padx=5, pady=8)
        
        page_frame = Frame(options_frame, bg="#f5f5f5")
        page_frame.grid(row=0, column=1, sticky=W, padx=5, pady=8)
        
        Label(page_frame, text="从", bg="#f5f5f5").pack(side=LEFT)
        self.start_page = Entry(page_frame, width=5, font=("微软雅黑", 9))
        self.start_page.pack(side=LEFT, padx=2)
        self.start_page.insert(0, "1")
        
        Label(page_frame, text="到", bg="#f5f5f5").pack(side=LEFT, padx=(5,0))
        self.end_page = Entry(page_frame, width=5, font=("微软雅黑", 9))
        self.end_page.pack(side=LEFT, padx=2)
        self.end_page.insert(0, "全部")
        
        # 批量转换选项
        self.batch_mode = BooleanVar()
        batch_cb = Checkbutton(options_frame, text="批量转换（转换文件夹内所有PDF文件）", 
                               variable=self.batch_mode,
                               font=("微软雅黑", 10), bg="#f5f5f5",
                               command=self.toggle_batch_mode)
        batch_cb.grid(row=1, column=0, columnspan=2, sticky=W, padx=5, pady=8)
        
        # 按钮区域
        btn_frame = Frame(main_frame, bg="#f5f5f5")
        btn_frame.pack(fill=X, pady=10)
        
        self.convert_btn = Button(btn_frame, text="开始转换", 
                                 command=self.start_conversion,
                                 font=("微软雅黑", 12, "bold"), 
                                 bg="#e74c3c", fg="white", width=15)
        self.convert_btn.pack(side=LEFT, padx=5)
        
        self.stop_btn = Button(btn_frame, text="停止转换", 
                              command=self.stop_conversion_process,
                              font=("微软雅黑", 12), 
                              bg="#95a5a6", fg="white", width=15,
                              state=DISABLED)
        self.stop_btn.pack(side=LEFT, padx=5)
        
        # 进度条
        self.progress = ttk.Progressbar(main_frame, mode='indeterminate')
        self.progress.pack(fill=X, pady=5)
        
        # 状态显示
        self.status_var = StringVar()
        self.status_var.set("就绪 - 选择PDF文件开始转换")
        status_label = Label(main_frame, textvariable=self.status_var,
                            font=("微软雅黑", 10), bg="#f5f5f5", fg="#2c3e50")
        status_label.pack(fill=X, pady=5)
        
        # 日志显示区域
        log_frame = LabelFrame(main_frame, text="转换日志", 
                              font=("微软雅黑", 11, "bold"),
                              bg="#f5f5f5", fg="#2c3e50")
        log_frame.pack(fill=BOTH, expand=True, pady=(10, 0))
        
        # 创建滚动文本框显示日志
        self.log_text = Text(log_frame, height=8, wrap=WORD, 
                           font=("Consolas", 9), bg="#2c3e50", fg="#ecf0f1")
        scrollbar = Scrollbar(log_frame, command=self.log_text.yview)
        self.log_text.configure(yscrollcommand=scrollbar.set)
        
        self.log_text.pack(side=LEFT, fill=BOTH, expand=True)
        scrollbar.pack(side=RIGHT, fill=Y)
        
        self.log_text.insert(END, f"PDF转Word转换器已启动 - 作者: {AUTHOR_NAME}\n")
        self.log_text.insert(END, "="*50 + "\n")
        
    def toggle_batch_mode(self):
        """切换批量转换模式"""
        if self.batch_mode.get():
            self.pdf_path.set("")  # 清空单个文件路径
            self.status_var.set("批量模式：请选择包含PDF文件的文件夹")
        else:
            self.status_var.set("单文件模式：请选择PDF文件")
    
    def select_pdf_file(self):
        """选择PDF文件"""
        if self.batch_mode.get():
            folder_path = filedialog.askdirectory(title="选择包含PDF文件的文件夹")
            if folder_path:
                self.pdf_path.set(folder_path)
                pdf_count = len([f for f in os.listdir(folder_path) if f.lower().endswith('.pdf')])
                self.log_text.insert(END, f"✓ 已选择文件夹: {folder_path} (包含 {pdf_count} 个PDF文件)\n")
                self.log_text.see(END)
        else:
            file_path = filedialog.askopenfilename(
                title="选择PDF文件",
                filetypes=[("PDF文件", "*.pdf"), ("所有文件", "*.*")]
            )
            if file_path:
                self.pdf_path.set(file_path)
                self.log_text.insert(END, f"✓ 已选择PDF文件: {os.path.basename(file_path)}\n")
                self.log_text.see(END)
    
    def select_output_folder(self):
        """选择输出文件夹"""
        folder_path = filedialog.askdirectory(title="选择Word文件保存位置")
        if folder_path:
            self.output_path.set(folder_path)
            self.log_text.insert(END, f"✓ 输出目录: {folder_path}\n")
            self.log_text.see(END)
    
    def validate_inputs(self):
        """验证输入参数"""
        if not self.pdf_path.get():
            messagebox.showerror("错误", "请先选择PDF文件或文件夹！")
            return False
        
        if not self.output_path.get():
            messagebox.showerror("错误", "请选择输出目录！")
            return False
        
        # 验证页面范围
        try:
            if self.start_page.get() and self.start_page.get() != "全部":
                start = int(self.start_page.get())
                if start < 1:
                    raise ValueError("起始页必须大于0")
        except ValueError:
            messagebox.showerror("错误", "起始页必须是大于0的整数！")
            return False
            
        return True
    
    def hide_main_window(self):
        """隐藏主窗口[6,7](@ref)"""
        # 使用withdraw()方法隐藏主窗口[7](@ref)
        self.root.withdraw()
        self.log_text.insert(END, "主窗口已隐藏，转换完成后自动显示\n")
        self.log_text.see(END)
    
    def show_main_window(self):
        """显示主窗口[7](@ref)"""
        # 使用deiconify()方法重新显示主窗口[7](@ref)
        self.root.deiconify()
        self.log_text.insert(END, "主窗口已显示\n")
        self.log_text.see(END)

    def set_word_properties(self, word_file_path, original_pdf_path=None):
        """设置Word文档属性并修改时间"""
        try:
            doc = Document(word_file_path)
            
            # 修改作者信息
            doc.core_properties.author = AUTHOR_NAME
            doc.core_properties.last_modified_by = AUTHOR_NAME
            
            # 清空备注信息
            doc.core_properties.comments = ""
            doc.core_properties.keywords = ""
            doc.core_properties.subject = ""
            current_time = time.time()
            # 设置时间属性
            # 设置为Word文档的创建和修改时间
            doc.core_properties.created = datetime.fromtimestamp(current_time)
            doc.core_properties.modified = datetime.fromtimestamp(current_time)
            
            doc.save(word_file_path)
            return True
        except Exception as e:
            self.log_text.insert(END, f"警告: 无法设置文档属性: {str(e)}\n")
            return False
    
    def start_conversion(self):
        """开始转换过程"""
        if not self.validate_inputs():
            return
        
        # 隐藏主窗口[6,7](@ref)
        self.hide_main_window()
        
        self.convert_btn.config(state=DISABLED, bg="#95a5a6")
        self.stop_btn.config(state=NORMAL, bg="#e74c3c")
        self.progress.start(10)
        self.stop_conversion = False
        
        # 在新线程中执行转换
        self.conversion_thread = threading.Thread(target=self.convert_pdf_to_word)
        self.conversion_thread.daemon = True
        self.conversion_thread.start()
    
    def stop_conversion_process(self):
        """停止转换过程"""
        self.stop_conversion = True
        self.status_var.set("正在停止转换...")
        self.log_text.insert(END, "⚠ 用户请求停止转换...\n")
        self.log_text.see(END)
    
    def convert_pdf_to_word(self):
        """执行PDF到Word的转换"""
        try:
            if self.batch_mode.get():
                self.batch_convert_pdfs()
            else:
                self.single_convert_pdf()
        except Exception as e:
            self.root.after(0, lambda: self.conversion_failed(str(e)))
        finally:
            # 无论转换成功还是失败，都显示主窗口
            self.root.after(0, self.show_main_window)
    
    def single_convert_pdf(self):
        """转换单个PDF文件"""
        pdf_file = self.pdf_path.get()
        output_dir = self.output_path.get()
        
        # 生成输出文件名
        pdf_name = os.path.splitext(os.path.basename(pdf_file))[0]
        output_file = os.path.join(output_dir, f"{pdf_name}.docx")
        
        self.root.after(0, lambda: self.status_var.set(f"正在转换: {os.path.basename(pdf_file)}"))
        
        try:
            # 执行转换[1,3](@ref)
            cv = Converter(pdf_file)
            
            # 设置页面范围
            start_page = 0
            end_page = None
            
            if self.start_page.get() and self.start_page.get() != "全部":
                start_page = int(self.start_page.get()) - 1  # 转换为0基索引
                if self.end_page.get() and self.end_page.get() != "全部":
                    end_page = int(self.end_page.get())
            
            cv.convert(output_file, start=start_page, end=end_page)
            cv.close()
            
            # 设置Word文档属性并清空备注[7,8](@ref)
            self.set_word_properties(output_file)
            
            if not self.stop_conversion:
                self.root.after(0, lambda: self.conversion_success(pdf_file, output_file))
            else:
                self.root.after(0, self.conversion_stopped)
                
        except Exception as e:
            if not self.stop_conversion:
                raise e
    
    def batch_convert_pdfs(self):
        """批量转换PDF文件"""
        input_dir = self.pdf_path.get()
        output_dir = self.output_path.get()
        
        # 获取所有PDF文件
        pdf_files = [f for f in os.listdir(input_dir) if f.lower().endswith('.pdf')]
        
        if not pdf_files:
            self.root.after(0, lambda: messagebox.showwarning("警告", "选择的文件夹中没有PDF文件！"))
            self.root.after(0, self.conversion_completed)
            return
        
        success_count = 0
        total_count = len(pdf_files)
        
        for i, pdf_file in enumerate(pdf_files):
            if self.stop_conversion:
                break
                
            pdf_path = os.path.join(input_dir, pdf_file)
            output_file = os.path.join(output_dir, f"{os.path.splitext(pdf_file)[0]}.docx")
            
            self.root.after(0, lambda f=pdf_file, idx=i+1, total=total_count: 
                          self.status_var.set(f"正在转换 ({idx}/{total}): {f}"))
            
            try:
                cv = Converter(pdf_path)
                cv.convert(output_file)
                cv.close()
                
                # 设置Word文档属性并清空备注[7,8](@ref)
                self.set_word_properties(output_file)
                
                success_count += 1
                
                self.root.after(0, lambda f=pdf_file: self.log_text.insert(END, f"转换成功: {f}\n"))
                self.root.after(0, lambda: self.log_text.see(END))
                
            except Exception as e:
                self.root.after(0, lambda f=pdf_file, err=str(e): 
                              self.log_text.insert(END, f"转换失败 {f}: {err}\n"))
                self.root.after(0, lambda: self.log_text.see(END))
        
        if not self.stop_conversion:
            self.root.after(0, lambda: self.batch_conversion_completed(success_count, total_count))
        else:
            self.root.after(0, self.conversion_stopped)
    
    def conversion_success(self, pdf_file, output_file):
        """单个文件转换成功"""
        self.progress.stop()
        self.convert_btn.config(state=NORMAL, bg="#e74c3c")
        self.stop_btn.config(state=DISABLED, bg="#95a5a6")
        
        self.status_var.set("转换完成！")
        if(self.isAuto):
            sys.exit()
        
        self.log_text.insert(END, f"转换成功: {os.path.basename(pdf_file)} → {os.path.basename(output_file)}\n")
        self.log_text.insert(END, f"   作者已设置为: {AUTHOR_NAME}, 备注已清空\n")
        self.log_text.see(END)
        
        messagebox.showinfo("转换成功", 
                          f"PDF文件已成功转换为Word文档！\n\n"
                          f"原文件: {os.path.basename(pdf_file)}\n"
                          f"新文件: {os.path.basename(output_file)}\n"
                          f"作者: {AUTHOR_NAME}\n"
                          f"备注: 已清空\n"
                          f"保存位置: {os.path.dirname(output_file)}")
    
    def batch_conversion_completed(self, success_count, total_count):
        """批量转换完成"""
        self.progress.stop()
        self.convert_btn.config(state=NORMAL, bg="#e74c3c")
        self.stop_btn.config(state=DISABLED, bg="#95a5a6")
        
        self.status_var.set(f"批量转换完成: {success_count}/{total_count} 个文件成功")
        self.log_text.insert(END, f"🎉 批量转换完成! 成功: {success_count}/{total_count} 个文件\n")
        self.log_text.insert(END, f"   所有文档作者已设置为: {AUTHOR_NAME}, 备注已清空\n")
        self.log_text.see(END)
        
        messagebox.showinfo("批量转换完成", 
                          f"批量转换处理完成！\n\n"
                          f"总文件数: {total_count}\n"
                          f"成功转换: {success_count}\n"
                          f"作者: {AUTHOR_NAME}\n"
                          f"备注: 已清空\n"
                          f"失败: {total_count - success_count}")
    
    def conversion_stopped(self):
        """转换被用户停止"""
        self.progress.stop()
        self.convert_btn.config(state=NORMAL, bg="#e74c3c")
        self.stop_btn.config(state=DISABLED, bg="#95a5a6")
        
        self.status_var.set("转换已停止")
        self.log_text.insert(END, "⏹ 转换过程已被用户停止\n")
        self.log_text.see(END)
    
    def conversion_failed(self, error_msg):
        """转换失败处理"""
        self.progress.stop()
        self.convert_btn.config(state=NORMAL, bg="#e74c3c")
        self.stop_btn.config(state=DISABLED, bg="#95a5a6")
        
        self.status_var.set("转换失败")
        self.log_text.insert(END, f"转换失败: {error_msg}\n")
        self.log_text.see(END)
        
        messagebox.showerror("转换失败", 
                           f"PDF转换过程中出现错误：\n\n{error_msg}\n\n"
                           f"请检查PDF文件是否损坏或被加密保护。")

    def change_path(cls, new_pdf_path, new_output_path):
        cls.pdf_path.set(new_pdf_path)  # 修改类变量
        cls.output_path.set(new_output_path)
        cls.isAuto=True
        cls.start_conversion()
        #sys.exit()

def main():
    """主函数"""
    root = Tk()
    app = PDFToWordConverter(root)

    print(f"程序名称: {sys.argv[0]}")
    print(f"传递的参数数量: {len(sys.argv) - 1}")
    
    if len(sys.argv) > 1:
        print("传递的参数:")
        for i, arg in enumerate(sys.argv[1:], 1):
            print(f"  参数 {i}: {arg}")
            if(2==i):
                pdf_path_=sys.argv[1]
                output_path_=sys.argv[2]
                app.change_path(pdf_path_,output_path_)        

    root.mainloop()


if __name__ == "__main__":
    main()